from django.template import RequestContext
from django.contrib.auth.decorators import permission_required
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt


from host_install.models import InstallationOrder
from host_install.forms import InstallationOrderForm, SearchOrderForm

from common.diggpaginator import DiggPaginator
from common.decorator import post_validation


@permission_required("host_install.can_access_host_install")
def modify(request, order_id=None):
    if order_id:
        order = get_object_or_404(InstallationOrder, pk=order_id)
    else:
        order = None
    form = InstallationOrderForm(request.POST or None, instance=order)
    if request.POST and form.is_valid():
        action = request.POST["submit_button"]
        if order_id and action == "delete":
            form.instance.delete()
        if action != "delete":
            inst = form.save()
        if action == "save":
            return redirect("host_install.modify", inst.id)
        if order_id and action == "new":
            return redirect("host_install.new")
        if action in ("return", "delete"):
            return redirect("host_install.list")
        form = InstallationOrderForm()
    return render_to_response("host_install/order.html",
                              {"form": form,
                               "foreign": {'site': {
                                            'perm': request.user.has_perm("common.add_client"),
                                            'address': 'common/client'},
                                          'supplier': {
                                            'perm': request.user.has_perm('clariadmin.add_supplier'),
                                            'address': 'clariadmin/supplier'},
                                          'type': {
                                            'perm': request.user.has_perm("clariadmin.add_hosttype"),
                                            'address': 'clariadmin/hosttype'}},
                              }, context_instance=RequestContext(request))


@permission_required("host_install.can_access_host_install")
def list_all(request):
    columns = list(InstallationOrderForm.Meta.fields)
    columns.append("status")
    qs = InstallationOrder.objects.all()

    form = SearchOrderForm(request.POST or None)
    if request.POST and form.is_valid():
        qs = form.search(qs)
    # get sorting
    sort = "-id"
    sort_get = request.GET.get('sort',
                               request.session.get("sort_orders", sort))
    if sort_get in columns:
        sort = sort_get
    if sort_get.startswith('-') and sort_get[1:] in columns:
        sort = sort_get
    request.session["sort_orders"] = sort

    paginator = DiggPaginator(qs.order_by(sort), 70, body=5, tail=2, padding=2)

    # get page
    page_num = 1
    page_asked = int(request.GET.get('page', request.session.get('page_orders', 1)))
    if ((page_asked <= paginator.num_pages)):
        page_num = page_asked
    request.session["page_orders"] = page_num
    page = paginator.page(page_num)

    return render_to_response("host_install/list.html",
                              {"orders": page,
                               "columns": columns,
                               "form": form,
                               "sort": sort},
                              context_instance=RequestContext(request))


@csrf_exempt
@post_validation({"access_token": settings.HOST_INSTALL_FAI_TOKEN})
def get_host_config(request, serial_num):
    try:
        order = InstallationOrder.objects.get(serial=serial_num.lower())
    except (ObjectDoesNotExist, MultipleObjectsReturned), e:
        print "handle"
        raise e

    order.status = 2
    return render_to_response("host_install/config.html",
                              {'order': order},
                              context_instance=RequestContext(request))
